const app = getApp();
const util = require('../../../utils/util');
Page({

  data: {
    typeList: [],
    goodsImages: [],
    goodsCoverImages: [],
    goodsname: '',
    goodsprice: 0,
    goodsnumber: 1,
    typeId: 1,
    goodsintro: '',
    tempImgList: [],
    coverImages:''
    // currentIndex:0,
  },

  onLoad: function (options) {
  },
  onShow: function (options) {
    this.getCategory();
  },
  // 获取商品分类信息
  getCategory() {
    wx.request({
      url: `${app.globalData.baseurl}category/`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode == 200) {
          this.setData({
            typeList: res.data
          });
          // console.log(this.data.typeList);
        }
      },
      fail: (err) => {
        console.log('error!');
      }
    })
  },
  getType(event) {
    // console.log(event.currentTarget.dataset.index);
    let index = event.currentTarget.dataset.index;
    this.setData({
      currentIndex: event.currentTarget.dataset.index,
      typeId: this.data.typeList[index].sortid
    })
    console.log(this.data.typeId);
  },
  // 添加商品到数据库
  addGood(event) {
    console.log(event);
  },
  // async getImageBase64_readFile(tempFilePath) {
  //   const base64 = await new Promise(resolve => {
  //     //获取全局唯一的文件管理器 
  //     wx.getFileSystemManager().readFile({ //读取本地文件内容
  //       filePath: tempFilePath, // 文件路径
  //       encoding: 'base64', // 返回格式
  //       success: ({
  //         data
  //       }) => {
  //         // return resolve('data:image/png;base64,' + data);
  //         return resolve(data);
  //       }
  //     });
  //   });
  //   this.setData({
  //     coverImages:base64
  //   })
  //   console.log(base64);
  //   console.log(this.data.coverImages);
  // },
  // 选择商品的封面图
  chooseCoverImage() {
    let tempFilePaths = [];
    let list = this.data.goodsCoverImages;
    var that = this;
    wx.chooseImage({
      count: 1 - that.data.goodsCoverImages.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res);
        // console.log(res.tempFilePaths);
        tempFilePaths = res.tempFilePaths;
        // console.log(tempFilePaths);
        that.setData({
          goodsCoverImages: list.concat(tempFilePaths),
          tempImgList: res.tempFilePaths
        })
        that.uploadImageDetail();
      },
    })
  },
  // 选择详情图片
  chooseDetailImage() {
    let tempFilePaths = [];
    let list = this.data.goodsImages;
    var that = this;
    wx.chooseImage({
      count: 9 - that.data.goodsImages.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res);
        console.log(res.tempFilePaths);
        tempFilePaths = res.tempFilePaths;
        console.log(111);
        console.log(tempFilePaths);
        // that.uploadImageDetail();
        that.setData({
          goodsImages: list.concat(tempFilePaths),
          tempImgList: res.tempFilePaths
        })
        console.log(that.data.goodsImages);
      },
    })
  },
  // 上传详情图片到后端存储
  uploadImageDetail() {
    var that = this;
    for (let i in this.data.tempImgList) {
      wx.uploadFile({
        url:'',
        filePath: `this.data.tempImgList[${i}]`,
        success(res) {
          console.log(res.fileId);
          that.data.goodsCoverImages.push(res.fileId);
          that.setData({
            goodsCoverImages: that.data.goodsCoverImages
          })
        }
      })
    }
  },
  // 删除封面图片
  deleteCoverImage(event) {
    console.log(event.currentTarget.dataset.index);
    this.data.goodsCoverImages.splice(event.currentTarget.dataset.index, 1);
    this.setData({
      goodsCoverImages: this.data.goodsCoverImages
    })
  },
  // 删除详情图片
  deleteDetailImage(event) {
    console.log(event.currentTarget.dataset.index);
    this.data.goodsImages.splice(event.currentTarget.dataset.index, 1);
    this.setData({
      goodsImages: this.data.goodsImages
    })
  },
  // 获取商品名字
  getGoodsName(event) {
    console.log(event.detail.value);
    this.setData({
      goodsname: event.detail.value
    })
    console.log(this.data.goodsname);
  },
  // 获取商品价格
  getGoodsPrice(event) {
    this.setData({
      goodsprice: event.detail.value
    })
    console.log(this.data.goodsprice);

  },
  // 获取商品数量
  getGoodsNumber(event) {
    this.setData({
      goodsnumber: event.detail.value
    })
    console.log(this.data.goodsnumber);
  },
  // 获取商品描述
  getGoodsDescribe(event) {
    this.setData({
      goodsintro: event.detail.value
    })
    console.log(this.data.goodsintro);
  },
  // 
  // setFile(data) {
  //   // 将wx.chooseImage返回的数据进行扩展
  //   data.map((item, index) => {
  //     // 通过路径截取文件后缀名
  //     const fileFormat = item.path.substring(item.path.lastIndexOf(".") + 1, item.path.length);
  //     // wx.getFileSystemManager()小程序文件管理器api，可以将通过文件路径将其转换成64编码
  //     const fileManager = wx.getFileSystemManager();
  //     const base64 = fileManager.readFileSync(item.path, 'base64');
  //     item.fileContent = base64;
  //     item.fileSize = item.size;
  //     // 通过时间获取随机13位随机数并且拼接文件后缀进行文件命名
  //     item.fileName = this.getFileName(13) + '.' + fileFormat;
  //     // 此处操作是用来进行选中图片显示的，只有这样拼接才能显示base64编码的路径
  //     item.path = `data:image/${fileFormat};base64,${base64}`;;
  //   })
  //   this.setData({
  //     goodsCoverImages: this.data.goodsCoverImages.concat(data)
  //   });
  //   // 此处操作是用来将获取到的文件数据传递给父组件进行文件上传
  //   // this.triggerEvent('imageChange', this.data.fileList)
  // },
  // // 自动生成名字
  // getFileName(m) {
  //   m = m > 13 ? 13 : m;
  //   var num = new Date().getTime();
  //   return num.toString().substring(13 - m);
  // },
  // 发布商品
  publicGoods() {
    // console.log("这是发布");
    if (app.globalData.userInfo == null) {
      wx.showToast({
        icon: 'error',
        title: '未登录',
      })
      return;
    }
    wx.request({
      url: `${app.globalData.baseurl}goods/public`,
      method: "POST",
      data: {
        openid: app.globalData.openid,
        goodsImages: this.data.goodsImages,
        // goodsCoverImages: this.data.goodsCoverImages,
        goodsCoverImages: this.data.coverImages,
        goodsname: this.data.goodsname,
        goodsprice: this.data.goodsprice,
        goodsnumber: this.data.goodsnumber,
        typeId: this.data.typeId,
        goodsintro: this.data.goodsintro,
        username: app.globalData.userInfo.nickName,
        time: util.formatTime(new Date),
      },
      success: res => {
        console.log(res);
        console.log(res.data);
        wx.switchTab({
          url: '../../index/index',
        })

      },
    })
    this.setData({
      typeList: [],
      goodsImages: [],
      goodsCoverImages: [],
      goodsname: '',
      goodsprice: 0,
      goodsnumber: 1,
      typeId: 1,
      goodsintro: ''
    })
  }
})